package com.tom.websocket;

import cn.hutool.core.collection.CollUtil;
import io.netty.channel.Channel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会话管理
 * 用户id和channel的管理关系处理
 *
 * @author zx
 * @date 2024年10月18日 10:22
 */
public class UserChannelSession {
    /**
     * 用于多端多设备同时接收消息,允许同一个账号在多个设备同时在线,比如IPad与iPhone都能同时接收到消息
     * key: 用户ID，value： 多个channel
     */
    private static Map<String, List<Channel>> multiSession = new HashMap<>();

    /**
     * 用于记录用户id和客户端端longId的关联关系
     * key: longId ,value: 用户ID
     */
    private static Map<String, String> userChanelIdRelation = new HashMap<>();


    public static void putUserChanelIdRelation(String channelId, String userId) {
        userChanelIdRelation.put(channelId, userId);
    }

    public static String getUserIdByChanelId(String channelId) {
        return userChanelIdRelation.get(channelId);
    }


    /**
     * 建立链接后初始化用户会话
     *
     * @param userId
     * @param channel
     */
    public static void putMultiChannels(String userId, Channel channel) {
        List<Channel> channels = getMultiChannels(userId);
        if (channels == null || channels.size() == 0) {
            channels = new ArrayList<>();
        }
        channels.add(channel);
        multiSession.put(userId, channels);
    }

    public static List<Channel> getMultiChannels(String userId) {
        return multiSession.get(userId);
    }

    public static void outPutMulti() {
        System.out.println("--------------------------------------");
        for (Map.Entry<String, List<Channel>> entry : multiSession.entrySet()) {
            List<Channel> value = entry.getValue();
            String key = entry.getKey();
            System.out.println("++++++++++++++++++");
            System.out.println("UserId:" + key);
            for (Channel channel : value) {
                System.out.println("\t\tchannelId:" + channel.id().asLongText());
            }

            System.out.println("++++++++++++++++++");
        }

        System.out.println("--------------------------------------");


    }

    /**
     * 移除无用的channel会话
     *
     * @param userId
     * @param channelId
     */
    public static void removeUselessChannels(String userId, String channelId) {

        List<Channel> channels = getMultiChannels(userId);
        if(CollUtil.isEmpty(channels)){
            return;
        }
        for (int i = 0; i < channels.size(); i++) {
            Channel tempChannel = channels.get(i);
            if (tempChannel.id().asLongText().equals(channelId)) {
                channels.remove(i);
            }
        }
        if (channels.size() > 0) {
            multiSession.put(userId, channels);
        } else {
            multiSession.remove(userId);
        }
    }


}
